package com.woyou.ui.adapter;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.List;

import com.citaq.ideliver.R;
import com.squareup.picasso.Picasso;
import com.woyou.bean.ShopItem;
import com.woyou.ui.component.fastscroll.IViewHolder;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.eventbus.EventDeleteShop;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;

/**
 * 商户列表数据适配器
 * 
 * @author longtao.li
 * 
 */
public class MyShopListAdapter extends BaseAdapter implements OnClickListener {

	private List<ShopItem> items;
	private Context mContext;
	private Drawable defDrawable;
	private Drawable start0;
	private Drawable start0_5;
	private Drawable start1;
	private Drawable start1_5;
	private Drawable start2;
	private Drawable start2_5;
	private Drawable start3;
	private Drawable start3_5;
	private Drawable start4;
	private Drawable start4_5;
	private Drawable start5;
	private static final int REF_NUM = 5;
	private static final String TAG = "MyShopListAdapter";
//	private int loadFlag = REF_NUM;

	public MyShopListAdapter(List<ShopItem> items, Context context) {
		EventBus.getDefault().register(this);

		this.items = items;
		mContext = context;
		Resources res = mContext.getResources();
		// Bitmap bitmap = BitmapFactory.decodeResource(res, R.raw.tu);
		// Bitmap temp1 = BitmapFactory.decodeResource(res,
		// R.raw.status_business);
		// Bitmap temp2 = BitmapFactory.decodeResource(res, R.raw.status_rest);
		// Bitmap temp3 = BitmapFactory.decodeResource(mContext.getResources(),
		// R.raw.status_reserve);

		Bitmap bitmap = readBitMap(mContext, R.raw.tu);

		defDrawable = new BitmapDrawable(res, bitmap);

		// Bitmap s0 = BitmapFactory.decodeResource(res, R.raw.start0);
		// Bitmap s0_5 = BitmapFactory.decodeResource(res, R.raw.start0_5);
		// Bitmap s1 = BitmapFactory.decodeResource(res, R.raw.start1);
		// Bitmap s1_5 = BitmapFactory.decodeResource(res, R.raw.start1_5);
		// Bitmap s2 = BitmapFactory.decodeResource(res, R.raw.start2);
		// Bitmap s2_5 = BitmapFactory.decodeResource(res, R.raw.start2_5);
		// Bitmap s3 = BitmapFactory.decodeResource(res, R.raw.start3);
		// Bitmap s3_5 = BitmapFactory.decodeResource(res, R.raw.start3_5);
		// Bitmap s4 = BitmapFactory.decodeResource(res, R.raw.start4);
		// Bitmap s4_5 = BitmapFactory.decodeResource(res, R.raw.start4_5);
		// Bitmap s5 = BitmapFactory.decodeResource(res, R.raw.start5);

		Bitmap s0 = readBitMap(mContext, R.raw.start0);
		Bitmap s0_5 = readBitMap(mContext, R.raw.start0_5);
		Bitmap s1 = readBitMap(mContext, R.raw.start1);
		Bitmap s1_5 = readBitMap(mContext, R.raw.start1_5);
		Bitmap s2 = readBitMap(mContext, R.raw.start2);
		Bitmap s2_5 = readBitMap(mContext, R.raw.start2_5);
		Bitmap s3 = readBitMap(mContext, R.raw.start3);
		Bitmap s3_5 = readBitMap(mContext, R.raw.start3_5);
		Bitmap s4 = readBitMap(mContext, R.raw.start4);
		Bitmap s4_5 = readBitMap(mContext, R.raw.start4_5);
		Bitmap s5 = readBitMap(mContext, R.raw.start5);

		start0 = new BitmapDrawable(res, s0);
		start0_5 = new BitmapDrawable(res, s0_5);
		start1 = new BitmapDrawable(res, s1);
		start1_5 = new BitmapDrawable(res, s1_5);
		start2 = new BitmapDrawable(res, s2);
		start2_5 = new BitmapDrawable(res, s2_5);
		start3 = new BitmapDrawable(res, s3);
		start3_5 = new BitmapDrawable(res, s3_5);
		start4 = new BitmapDrawable(res, s4);
		start4_5 = new BitmapDrawable(res, s4_5);
		start5 = new BitmapDrawable(res, s5);

	}

	int state = 0;// 0：未编辑状态 1：编辑状态

	public void onEvent(EventDeleteShop event) {
		state = 1;
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return items.size();
	}

	@Override
	public Object getItem(int position) {
		return items.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	int count = 0;

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Log.i(TAG, "position=" + position + "  count=" + count);
		count++;
		ViewHolder holder;
		if (convertView == null) {
			convertView = View.inflate(mContext, R.layout.item_myshop, null);
			holder = new ViewHolder();
			holder.sName = (TextView) convertView.findViewById(R.id.name);
			holder.addrOrNotice = (TextView) convertView
					.findViewById(R.id.addrOrNotice);
			holder.starts = (ImageView) convertView.findViewById(R.id.starts);
			holder.commentsNum = (TextView) convertView
					.findViewById(R.id.commentsNum);
			holder.state = (TextView) convertView.findViewById(R.id.state);
			holder.isOnlinePay=(ImageView)convertView.findViewById(R.id.isOnlinePay);
			holder.distance = (TextView) convertView
					.findViewById(R.id.distance);
			holder.prompt = (TextView) convertView.findViewById(R.id.prompt);
			holder.img = (ImageView) convertView.findViewById(R.id.shop_pic_iv);
			holder.re_delete = (LinearLayout) convertView
					.findViewById(R.id.re_delete);
			holder.re_textstate = (RelativeLayout) convertView
					.findViewById(R.id.re_textstate);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if (state == 1) {
			holder.re_delete.setVisibility(View.VISIBLE);
			holder.re_textstate.setVisibility(View.GONE);
		}
		holder.img.setImageDrawable(defDrawable);
		ShopItem item = items.get(position);
		holder.item = item;
		// 先加载第一页图片
		if (!TextUtils.isEmpty(item.picUrl)) {
			if (position < 5) {
				loadIMG(holder.img, item);
			}
		} 
		holder.no = position;
		// String branch = "";
		// String shopName = "";
		// if( !TextUtils.isEmpty(item.sName) ){
		// int indexOf = item.sName.indexOf("(");
		// if( indexOf != -1 ){
		// shopName = item.sName.substring(0, indexOf );
		// branch = item.sName.substring(indexOf);
		// }else{
		// shopName = item.sName;
		// }
		// }
		// float dimension = mContext.getResources().getDimension(R.dimen.sp38);
		// float dimension1 =
		// mContext.getResources().getDimension(R.dimen.sp34);
		//
		// holder.sName.setTextSize(DensityUtil.px2sp(dimension, mContext));
		// int length = shopName.getBytes().length;
		// if( length > 27 ){
		// holder.sName.setTextSize(DensityUtil.px2sp(dimension1, mContext));
		// }
		// holder.sName.setText(shopName);
		// if( item.notice == null ){
		// holder.addrOrNotice.setText(branch);
		// }else{
		// holder.addrOrNotice.setText(item.notice);
		// }
		String[] sNameArray = item.sName.split("\\(");

		holder.sName.setText(sNameArray[0]);
		if (!item.notice.equals("")) {
			holder.addrOrNotice.setText(item.notice);
		} else if (sNameArray.length > 1) {
			holder.addrOrNotice.setText("(" + sNameArray[1]);
		} else {
			holder.addrOrNotice.setText("");
		}

		String disStr = getDisStr(item.distance);
		holder.distance.setText(disStr);
		holder.commentsNum.setText("(" + item.getCommentsNum() + ")");

		// 20元起送 / 月售200份
		String prompt = "";
		String spending = ParseUtils.String2Money(item.spending);
		if(item.state==1 || item.state==3)
		{
			if ( spending.indexOf("-") != -1) {
				prompt = "- / ";
			} 
			else
			{
				prompt = ParseUtils.String2Money(item.spending) + "元起送 / ";
			}
		}
		else 
		{
			prompt = "- /";
		}
		
		if (!TextUtils.isEmpty(item.avgSend) && Integer.parseInt(item.avgSend)>=0) {
			prompt = prompt + "月售" + item.salesQty + "份";
		}
		else
		{
			prompt = prompt + "月售0份";
		}

		holder.prompt.setText(prompt);
		//1：营业 2:休息 3:繁忙 4:超出范围
		if( item.state == 1 ){
			holder.state.setText("营业");
			holder.state.setBackgroundResource(R.drawable.shopstatus_business);
		}else if( item.state == 2 ){
			holder.state.setText("休息");
			holder.state.setBackgroundResource(R.drawable.shopstatus_rest);
		}else if( item.state == 3 ){
			holder.state.setText("仅预定");
			holder.state.setBackgroundResource(R.drawable.shopstatus_busy);
		}else if( item.state == 4 ){
			holder.state.setText("超出范围");
			holder.state.setBackgroundResource(R.drawable.shopstatus_out);
		}
		//店铺是否支持在线支付
		if(item.isOnlinePay==1){
			holder.isOnlinePay.setVisibility(View.VISIBLE);
		}else{
			holder.isOnlinePay.setVisibility(View.GONE);
		}
		// 星级
		setPraiseRate(holder.starts, item.score);

		// 删除按钮
		holder.re_delete.setTag(holder);
		holder.re_delete.setOnClickListener(this);
		return convertView;
	}

	/**
	 * ViewHolder
	 * 
	 * @author longtao.li
	 */
	 class ViewHolder implements IViewHolder {
		TextView sName;
		TextView addrOrNotice;
		ImageView starts;
		TextView commentsNum;
		TextView state;
		ImageView isOnlinePay;
		TextView distance;
		TextView prompt;
		ImageView img;
		ShopItem item;
		LinearLayout re_delete;
		RelativeLayout re_textstate;
		int no;

		@Override
		public void load() {
			if (!TextUtils.isEmpty(item.getPicUrl())) {
				loadIMG(img, item);
			}
		}
	}

	public static StringBuffer sb;

	@Override
	public void onClick(View v) {
		ViewHolder viewHolder;
		switch (v.getId()) {
		case R.id.re_delete:
			viewHolder = (ViewHolder) v.getTag();
			sb.append(viewHolder.item.getsId() + "|");
			items.remove(viewHolder.no);
			notifyDataSetChanged();
			break;
		default:
			break;
		}
	}

	/**
	 * 加载图片
	 * 
	 * @param tuContainer
	 * @param item
	 */
	private  void loadIMG(final ImageView img, ShopItem item) {
		Picasso.with(mContext).load(item.getPicUrl()).placeholder(defDrawable).error(defDrawable).into(img);
	}

	@Override
	public void notifyDataSetChanged() {
		Log.i(TAG, "notifyDataSetChanged");
		count = 0;
//		loadFlag = 0;
		super.notifyDataSetChanged();
	}

	// 返回UI要显示的距离字符串
	private String getDisStr(String distance) {
		DecimalFormat df = new DecimalFormat("0.0");
		String disStr = "";

		double dis = 0;
		try {
			dis = Float.parseFloat(distance);
			if (dis < 1000) {
				disStr = (int) (dis / 1) + "m";
			} else {
				dis = dis / 1000;
				if (dis > 99) {
					return ">99km";
				}
				disStr = df.format(dis) + "km";
			}
		} catch (Exception e) {
		}
		return disStr;
	}

	private void setPraiseRate(ImageView img, float score) {
		if (score == 0) {
			img.setImageDrawable(start0);
		} else if (score <= 1) {
			img.setImageDrawable(start0_5);
		} else if (score <= 2) {
			img.setImageDrawable(start1);
		} else if (score <= 3) {
			img.setImageDrawable(start1_5);
		} else if (score <= 4) {
			img.setImageDrawable(start2);
		} else if (score <= 5) {
			img.setImageDrawable(start2_5);
		} else if (score <= 6) {
			img.setImageDrawable(start3);
		} else if (score <= 7) {
			img.setImageDrawable(start3_5);
		} else if (score <= 8) {
			img.setImageDrawable(start4);
		} else if (score <= 9) {
			img.setImageDrawable(start4_5);
		} else if (score <= 10) {
			img.setImageDrawable(start5);
		}
	}

	public Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}
}
